<template>
  <VZPanel title="故障里程分布(k公里)" simple iconText="mdi-chart-pie">
    <div style="margin:-16px">
      <v-card>
        <v-row>
          <v-col cols="3">
            <v-autocomplete
                    v-model="selectedReferred"
                    :items="referredItems"
                    item-text="text"
                    item-value="id"
                    label="搜索零件简称"
                    outlined
                    dense
                    clearable
                    :filter="customFilter"
                    :loading="loading"
                    multiple
            ></v-autocomplete>
          </v-col>
          <v-col cols="3">
            <v-autocomplete
                    v-model="selectedMaterial"
                    :items="materialItems"
                    item-text="text"
                    item-value="id"
                    label="搜索产品"
                    outlined
                    dense
                    clearable
                    :filter="customFilter"
                    :loading="loading"
            ></v-autocomplete>
          </v-col>
          <v-col cols="2">
            <v-menu
                    ref="startMenu"
                    v-model="startMenu"
                    :close-on-content-click="false"
                    max-width="290"
                    min-width="290"
                    offset-y
            >
              <template v-slot:activator="{ on, attrs }">
                <v-text-field
                        v-model="startYear"
                        label="起始日期"
                        readonly
                        v-bind="attrs"
                        v-on="on"
                        outlined
                        dense
                ></v-text-field>
              </template>
              <v-date-picker
                      v-model="startYear"
                      type="month"
                      @change="startMenu = false"
                      :max="endYear"
                      locale="zh-cn"
              ></v-date-picker>
            </v-menu>
          </v-col>
          <v-col cols="2">
            <v-menu
                    ref="endMenu"
                    v-model="endMenu"
                    :close-on-content-click="false"
                    max-width="290"
                    min-width="290"
                    offset-y
            >
              <template v-slot:activator="{ on, attrs }">
                <v-text-field
                        v-model="endYear"
                        label="结束日期"
                        readonly
                        v-bind="attrs"
                        v-on="on"
                        outlined
                        dense
                ></v-text-field>
              </template>
              <v-date-picker
                      v-model="endYear"
                      type="month"
                      @change="endMenu = false"
                      :min="startYear"
                      locale="zh-cn"
              ></v-date-picker>
            </v-menu>
          </v-col>
          <v-spacer></v-spacer>
          <v-col cols="auto" class="d-flex align-center">
            <v-tooltip bottom>
              <template v-slot:activator="{ on, attrs }">
                <v-btn
                  icon
                  color="success"
                  @click="exportExcel"
                  :disabled="loading"
                  class="mr-2"
                  v-bind="attrs"
                  v-on="on"
                  style="width: 36px; height: 36px"
                >
                  <v-icon size="24">mdi-file-excel</v-icon>
                </v-btn>
              </template>
              <span>导出Excel</span>
            </v-tooltip>
            <v-tooltip bottom>
              <template v-slot:activator="{ on, attrs }">
                <v-btn
                  icon
                  color="primary"
                  @click="exportChart"
                  :disabled="loading"
                  v-bind="attrs"
                  v-on="on"
                  style="width: 36px; height: 36px"
                >
                  <v-icon size="24">mdi-image</v-icon>
                </v-btn>
              </template>
              <span>导出图片</span>
            </v-tooltip>
          </v-col>
        </v-row>
        <div ref="target" style="width:100%;height:450px"></div>
        <v-data-table
                :headers="tableHeaders"
                :items="tableItems"
                :items-per-page="12"
                class="elevation-1"
                hide-default-footer
                dense
        >
          <template v-slot:item.range="{ item }">
            {{ item.range }}
          </template>
        </v-data-table>
      </v-card>
    </div>
  </VZPanel>
</template>

<script>
  export default {
    data() {
      return {
        chartTarget: null,
        nameList: [],
        numList: [],
        distanceRanges: [
          { min: 0, max: 100, label: '0-100' },
          { min: 100, max: 500, label: '100-500' },
          { min: 500, max: 1000, label: '500-1000' },
          { min: 1000, max: 5000, label: '1000-5000' },
          { min: 5000, max: 10000, label: '5000-10000' },
          { min: 10000, max: 50000, label: '10000-50000' },
          { min: 50000, max: 100000, label: '50000-100000' },
          { min: 100000, max: 150000, label: '100000-150000' }
        ],
        sql: "SELECT DATE_FORMAT(back_month, '%m') AS `name`,COUNT(*) AS num " +
                "FROM tt_sale_record_qms a " +
                "WHERE a.MATERIAL_ID = 135068 AND DATE_FORMAT(back_month, '%Y') = '2024'     " +
                "GROUP BY DATE_FORMAT(back_month, '%m') ORDER BY `name`; ",
        materialSql: "SELECT id,CONCAT(name,'   ',ASSEMBLY_CODE) name FROM tb_standard_assembly_product WHERE MARK_FOR_DELETE = 0",
        referredSql: "SELECT c.id,CONCAT(c.SIMPLE_CALL,'   ',c.CODE) name FROM tt_sale_record_qms a  " +
                "LEFT JOIN tb_standard_assembly_product b ON a.MATERIAL_ID = b.ID " +
                "LEFT JOIN tb_standard_assembly_product_referred c ON c.id = b.REFERRED_ID " +
                "WHERE c.SIMPLE_CALL IS NOT NULL  " +
                "GROUP BY c.ID ",
        materialItems: [],
        referredItems: [],
        searchMaterial: '',
        selectedMaterial: '',
        selectedReferred: [],
        yearOptions: [],
        startYear: '',
        endYear: '',
        startMenu: false,
        endMenu: false,
        loading: true,
        yearData: {},
        materialIds: [],
        tableHeaders: [
          { text: '里程区间(km)', value: 'range' },
          { text: '数量', value: 'count', align: 'center' }
        ],
        tableItems: [],
      }
    },
    computed: {
      years() {
        if (!this.startYear || !this.endYear) return [];
        const start = parseInt(this.startYear);
        const end = parseInt(this.endYear);
        return Array.from({length: end - start + 1}, (_, i) => String(start + i));
      }
    },
    methods: {
      run() {
        if (!this.chartTarget) {
          this.chartTarget = this.$echarts.init(this.$refs.target);
        }
        this.chartTarget.clear();
        let option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            formatter: (params) => {
              return `${params[0].name}<br/>数量: ${params[0].value}个`;
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: this.nameList,
            name: '里程区间(km)',
            axisLabel: {
              interval: 0,
              rotate: 45
            }
          },
          yAxis: {
            type: 'value',
            name: '数量',
            axisLabel: {
              formatter: '{value} 个'
            }
          },
          series: [{
            data: this.numList,
            type: 'bar',
            itemStyle: {
              normal: {
                label: {
                  show: true,
                  position: 'top',
                  textStyle: {
                    color: '#88aecc',
                    fontSize: 12
                  }
                }
              }
            }
          }]
        }
        this.chartTarget.setOption(option);
        
        // 添加图表点击事件
        let _this = this;
        this.chartTarget.on('click', function (params) {
            // 获取点击的里程区间
            let range = params.name;
            let startDate, endDate;
            
            // 使用当前选择的日期范围
            if (_this.startYear && _this.endYear) {
                startDate = `${_this.startYear}-01`;
                const lastDay = new Date(parseInt(_this.endYear.split('-')[0]), parseInt(_this.endYear.split('-')[1]), 0).getDate();
                endDate = `${_this.endYear}-${lastDay}`;
            } else {
                // 如果没有选择日期范围，使用默认的最近一个月
                const today = new Date();
                const lastMonth = new Date(today.getFullYear(), today.getMonth() - 1, 1);
                const lastDay = new Date(today.getFullYear(), today.getMonth(), 0).getDate();
                startDate = `${lastMonth.getFullYear()}-${String(lastMonth.getMonth() + 1).padStart(2, '0')}-01`;
                endDate = `${lastMonth.getFullYear()}-${String(lastMonth.getMonth() + 1).padStart(2, '0')}-${lastDay}`;
            }

            // 解析里程区间
            let [min, max] = range.split('-').map(Number);
            if (isNaN(min) || isNaN(max)) {
                app.$message.warning('无效的里程区间');
                return;
            }

            // 跳转到详情页面，传递必要参数
            _this.$emit('toPage', 'v4a964e28354dd5945af2da28ad', {
                material_id: _this.materialIds.join(','),
                drive_distance_min: min,
                drive_distance_max: max,
                btime: startDate,
                etime: endDate
            });
        });
      },
      search_data() {
        if (this.materialIds.length === 0) {
          return;
        }
        let _this = this;
        this.loading = true;
        const queries = this.distanceRanges.map(range => {
          const sql = `SELECT COUNT(*) as count
                        FROM tt_sale_record_qms a
                        WHERE a.MATERIAL_ID in (${this.materialIds.join(',')})
                        AND DATE_FORMAT(MADE_TIME, '%Y-%m') >= '${this.startYear}'
                        AND DATE_FORMAT(MADE_TIME, '%Y-%m') <= '${this.endYear}'
                        AND DRIVE_DISTANCE >= ${range.min}
                        AND DRIVE_DISTANCE <= ${range.max}`;
          return new Promise((resolve) => {
            app.utils.ajaxRequest({
              hideMsg: true,
              hideMask: true,
              url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
              params: {
                functionParam: JSON.stringify({ "SQL": sql })
              },
              callBack(res) {
                if (res.success) {
                  resolve({
                    range: range.label,
                    count: res.rows[0].count || 0
                  });
                } else {
                  resolve({
                    range: range.label,
                    count: 0
                  });
                }
              },
            });
          });
        });
        Promise.all(queries).then(results => {
          _this.tableItems = results;
          _this.nameList = results.map(item => item.range);
          _this.numList = results.map(item => item.count);
          _this.run();
          _this.loading = false;
        }).catch(() => {
          _this.loading = false;
        });
      },
      loadReferredData() {
        let _this = this;
        _this.referredItems = [];
        let params = {"SQL": this.referredSql};
        app.utils.ajaxRequest({
          hideMsg: true,
          hideMask: true,
          url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
          params: {
            functionParam: JSON.stringify(params)
          },
          callBack(res) {
            if (res.success && res.rows.length > 0) {
              let dataList = res.rows;
              let referredList = [];
              dataList.forEach((item) => {
                let map = {};
                map.text = item.name;
                map.id = item.id;
                referredList.push(map);
              })
              _this.referredItems = referredList;
              if (_this.referredItems.length > 0) {
                _this.selectedReferred = [_this.referredItems[0].id];
                _this.loadMaterialIdsByReferred().then(() => {
                  if (_this.materialIds.length > 0) {
                    _this.search_data();
                  }
                });
              }
            }
          },
        })
      },
      loadMaterialData() {
        let _this = this;
        _this.materialItems = [];
        let params = {"SQL": this.materialSql};
        app.utils.ajaxRequest({
          hideMsg: true,
          hideMask: true,
          url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
          params: {
            functionParam: JSON.stringify(params)
          },
          callBack(res) {
            if (res.success && res.rows.length > 0) {
              let dataList = res.rows;
              let materialList = [];
              dataList.forEach((item) => {
                let map = {};
                map.text = item.name;
                map.id = item.id;
                materialList.push(map);
              })
              _this.materialItems = materialList;
            }
            _this.loading = false;
          },
        })
      },
      loadMaterialIdsByReferred() {
        if (!this.selectedReferred.length) {
          this.materialIds = this.selectedMaterial ? [this.selectedMaterial] : [];
          return Promise.resolve();
        }
        let _this = this;
        let params = {
          "SQL": `SELECT DISTINCT a.id
                    FROM tb_standard_assembly_product a
                    WHERE a.MARK_FOR_DELETE = 0
                    AND a.REFERRED_ID IN (${this.selectedReferred.join(',')})`
        };
        return new Promise((resolve) => {
          app.utils.ajaxRequest({
            hideMsg: true,
            hideMask: true,
            url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
            params: {
              functionParam: JSON.stringify(params)
            },
            callBack(res) {
              if (res.success && res.rows.length > 0) {
                _this.materialIds = res.rows.map(item => item.id);
              } else {
                _this.materialIds = [];
              }
              resolve();
            },
          });
        });
      },
      initYearOptions() {
        const currentDate = new Date();
        const currentYear = currentDate.getFullYear();
        const currentMonth = String(currentDate.getMonth() + 1).padStart(2, '0');
        this.endYear = `${currentYear}-${currentMonth}`;
        const startDate = new Date(currentDate);
        startDate.setFullYear(currentYear - 3);
        this.startYear = `${startDate.getFullYear()}-${String(startDate.getMonth() + 1).padStart(2, '0')}`;
      },
      reset() {
        this.searchMaterial = '';
        this.selectedMaterial = '';
        this.selectedReferred = [];
        this.initYearOptions();
        this.search_data();
      },
      customFilter(item, queryText, itemText) {
        const textOne = itemText.toLowerCase();
        const searchText = queryText.toLowerCase();
        return textOne.indexOf(searchText) > -1;
      },
      exportExcel() {
        try {
          if (this.tableItems.length === 0) {
            app.$message.warning('没有可导出的数据');
            return;
          }
          
          // 创建CSV内容
          let csvContent = '里程区间(km),数量\n';
          this.tableItems.forEach(item => {
            csvContent += `${item.range},${item.count}\n`;
          });

          // 使用TextEncoder处理UTF-8编码
          const encoder = new TextEncoder();
          const data = encoder.encode('\ufeff' + csvContent);
          const blob = new Blob([data], { type: 'text/csv;charset=utf-8' });
          
          // 创建下载链接
          const link = document.createElement('a');
          link.href = URL.createObjectURL(blob);
          link.download = '故障里程分布.csv';
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          URL.revokeObjectURL(link.href);
        } catch (error) {
          console.error('导出Excel失败:', error);
          app.$message.error('导出Excel失败');
        }
      },
      exportChart() {
        if (!this.chartTarget) {
          return;
        }
        try {
          // 导出图表图片
          let base64 = this.chartTarget.getDataURL({
            type: 'png',
            pixelRatio: 2,
            backgroundColor: '#ffffff'
          });
          let link = document.createElement('a');
          link.download = '故障里程分布.png';
          link.href = base64;
          link.click();

          // 导出图表配置
          let option = this.chartTarget.getOption();
          let optionStr = JSON.stringify(option, null, 2);
          let optionBlob = new Blob([optionStr], { type: 'application/json' });
          let optionLink = document.createElement('a');
          optionLink.download = '故障里程分布配置.json';
          optionLink.href = URL.createObjectURL(optionBlob);
          optionLink.click();
        } catch (error) {
          console.error('导出图表失败:', error);
          app.$message.error('导出图表失败');
        }
      },
    },
    watch: {
      selectedMaterial() {
        if (this.selectedMaterial) {
          this.selectedReferred = [];
          this.materialIds = [this.selectedMaterial];
          this.$nextTick(() => {
            this.search_data();
          });
        }
      },
      async selectedReferred() {
        if (this.selectedReferred.length) {
          this.selectedMaterial = '';
          await this.loadMaterialIdsByReferred();
          if (this.materialIds.length > 0) {
            this.$nextTick(() => {
              this.search_data();
            });
          }
        } else {
          if (!this.selectedMaterial) {
            this.materialIds = [];
          }
        }
      },
      startYear() {
        if (this.materialIds.length > 0) {
          this.$nextTick(() => {
            this.search_data();
          });
        }
      },
      endYear() {
        if (this.materialIds.length > 0) {
          this.$nextTick(() => {
            this.search_data();
          });
        }
      }
    },
    created() {
      this.initYearOptions();
      this.loadMaterialData();
      this.loadReferredData();
      setTimeout(() => {
        this.search_data();
      }, 1000);
    },
    mounted() {
      window.onresize = () => {
        this.chartTarget.resize();
      }
    },
  }
</script>
